package com.fruit.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruit.pojo.user.UserInfo;
import com.fruit.resolver.DefiniteException;
import com.fruit.service.user.UserManager;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * WapLoginSecurityInterceptor
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
public class WapLoginSecurityInterceptor extends HandlerInterceptorAdapter {

	@Value("${app.key}")
	private String key;

	@Value("${domain}")
	private String contextPath;
	
	@Autowired
	private UserManager userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		Integer userId = (Integer) request.getSession().getAttribute("userId");
		UserInfo user = null;
		if (userId != null) {
			user = userService.getUser(userId);
		}

		String requestType = request.getHeader("X-Requested-With");
		if (user == null) {
			// 是否是AJAX登陆
			String forward = request.getServletPath();
			if (UrlConstant.urlMap.containsKey(forward)) {
				forward = UrlConstant.urlMap.get(forward);
			}
			String params = request.getQueryString();
			if (!StringUtils.isEmpty(params)) {
				forward += "?" + URLEncoder.encode(params, "UTF-8");
			}
			if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
				if (StringUtils.isEmpty(forward)) {
					response.sendRedirect(contextPath + "/wap/login/toLogin");
				} else {
					response.sendRedirect(contextPath + "/wap/login/toLogin?forward=" + forward+"&sourceChannel=0");
				}
			} else {
				Map<String, Object> resMap = new HashMap<String, Object>();
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "loginOut", "用户未登录", "/toLogin"));
				ObjectMapper om = new ObjectMapper();
				response.getWriter().print(om.writeValueAsString(resMap));
			}
			return false;
		}

		if (!"01".equals(user.getState())) {
			String msg = "该用户已经被禁用，请联系管理员";
			if (!StringUtils.equals(requestType, "XMLHttpRequest")) {
				throw new DefiniteException(msg);
			} else {
				Map<String, Object> resMap = new HashMap<String, Object>();
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", msg));
				ObjectMapper om = new ObjectMapper();
				response.getWriter().print(om.writeValueAsString(resMap));
			}
		}

		return true;
	}

}
